import React, { Component } from 'react'

import FilterTitle from '../FilterTitle'
import FilterPicker from '../FilterPicker'
import FilterMore from '../FilterMore'

import { Spring } from 'react-spring'

import styles from './index.module.css'

import API from '../../../../utils/api'

// 标题高亮状态
// true 表示高亮； false 表示不高亮
const titleSelectedStatus = {
  area: false,
  mode: false,
  price: false,
  more: false
}

// FilterPicker 和 FilterMore 组件的选中值
const selectedValues = {
  area: ['area', 'null'],
  mode: ['null'],
  price: ['null'],
  more: []
}

/* 
  获取当前筛选条件的数据：

  1 在 Filter 组件中，发送请求，获取所有筛选条件数据。
  2 将数据保存为状态：filtersData。
  3 封装渲染 FilterPicker 的方法 renderFilterPicker。

  4 在方法中，根据 openType 的类型，从 filtersData 中获取到需要的数据。
  5 将数据通过 props 传递给 FilterPicker 组件。
  6 FilterPicker 组件接收到数据后，将其作为 PickerView 组件的 data （数据源）。
*/


export default class Filter extends Component {
  state={
    //高亮样式的判定值
    titleSelectedStatus,
    //控制FilterPicker或者FilterMore组件的显示与隐藏
    openType: '',
    //所有筛选条件数据
    filtersData: [],
    //筛选条件的选中值
    selectedValues
  }
  componentDidMount(){
    this.getFiltersData()
    this.htmlBody=document.body
  }
  //封装获取所有筛选条件的方法
  async getFiltersData(){
    const {value: cityId} = JSON.parse(localStorage.getItem('hkzf_city')||'{}')
    const {data: res} = await API.get(`/houses/condition?id=${cityId}`)
    this.setState({
      filtersData: res.body
    })
  }

  //点击标题组件菜单实现高亮
  //需要要完整的功能需要后续组件配合完成
  onTitleClick=(type)=>{
    //给body添加样式
    this.htmlBody.className='body-fixed'
    const {titleSelectedStatus,selectedValues}  = this.state
    //创建新的标题选中状态对象
    const newTitleSelectedStatus={...titleSelectedStatus}
    //遍历标题选中状态对象
    Object.keys(titleSelectedStatus).forEach(key=>{
      if(key===type){
        //当前标题
        newTitleSelectedStatus[type]=true
        return
      }
      // //其他标题
      const selectedVal=selectedValues[key]
      if(key==='area'&&(selectedVal.length!==2||selectedVal[0]!=='area')){
        newTitleSelectedStatus[key]=true
      }else if(key==='mode'&&selectedVal[0]!=='null'){
        newTitleSelectedStatus[key]=true
      }else if(key==='price'&&selectedVal[0]!=='null'){
        newTitleSelectedStatus[key]=true
      }else if(key==='more'&&selectedVal.length!==0){
        //更多选择项Filtermore组件
        newTitleSelectedStatus[key]=true
      }else{
        newTitleSelectedStatus[key]=false
      }
    })
    this.setState({
      openType: type,
      titleSelectedStatus: newTitleSelectedStatus
    })
    // this.setState(prevState=>{
    //   return {
    //     titleSelectedStatus: {
    //       ...prevState.titleSelectedStatus,
    //       [type]: true
    //     },
    //     //展示对话框
    //     openType: type
    //   }
    // })
  
  }
  //取消(隐藏)对话框和遮罩层
  onCancle = (type) => {
    this.htmlBody.className=''
    //菜单高亮的逻辑处理
    // //其他标题
    const {titleSelectedStatus,selectedValues}  = this.state
    const selectedVal=selectedValues[type]
    const newTitleSelectedStatus={...titleSelectedStatus}
    if(type==='area'&&(selectedVal.length!==2||selectedVal[0]!=='area')){
      newTitleSelectedStatus[type]=true
    }else if(type==='mode'&&selectedVal[0]!=='null'){
      newTitleSelectedStatus[type]=true
    }else if(type==='price'&&selectedVal[0]!=='null'){
      newTitleSelectedStatus[type]=true
    }else if(type==='more'&&selectedVal.length!==0){
      //更多选择项Filtermore组件
      newTitleSelectedStatus[type]=true
    }else{
      newTitleSelectedStatus[type]=false
    }


    //隐藏对话框
    this.setState({
      openType: '',
      //更新菜单高亮状态数据
      titleSelectedStatus: newTitleSelectedStatus,
    }) 
  }
  //确定(隐藏对话框)
  onSave=(type,value)=>
  {
    this.htmlBody.className=''
    //菜单高亮的逻辑处理
    // //其他标题
    const selectedVal=value
    const {titleSelectedStatus}  = this.state
    const newTitleSelectedStatus={...titleSelectedStatus}
    if(type==='area'&&(selectedVal.length!==2||selectedVal[0]!=='area')){
      newTitleSelectedStatus[type]=true
    }else if(type==='mode'&&selectedVal[0]!=='null'){
      newTitleSelectedStatus[type]=true
    }else if(type==='price'&&selectedVal[0]!=='null'){
      newTitleSelectedStatus[type]=true
    }else if(type==='more'&&selectedVal.length!==0){
      //更多选择项Filtermore组件
      newTitleSelectedStatus[type]=true
    }else{
      newTitleSelectedStatus[type]=false
    }

    const newSelectedValues= {
      ...this.state.selectedValues,
      //只更新当前type对应的选中值
      [type]: value
    }

    //筛选条件数据
    const { area, mode, price, more }=newSelectedValues
    const filters={}

    //区域
    const areaKey=area[0]
    let areaValue=null
    if(area.length===3){
      areaValue=area[2]!=='null'?area[2]:area[1]
    }
    filters[areaKey]=areaValue

    //方式和租金
    filters.mode=mode[0]
    filters.price=price[0]

    //更多筛选条件
    filters.more=more.join(',')

    //调用父组件的onFilter方法将筛选数据传递给父组件
    const { onFilter } = this.props
    onFilter(filters)

    //隐藏对话框
    this.setState({
      openType: '',
      //更新菜单高亮状态数据
      titleSelectedStatus: newTitleSelectedStatus,
      selectedValues:newSelectedValues
    }) 
  }
  //渲染FilterPicker组件的方法
  renderFilterPicker(){
    const {openType,filtersData:{area,subway,rentType,price},selectedValues} = this.state
    if(!['area','mode','price'].includes(openType)){
      return null
    }

    //根据openType来拿到当前筛选条件的数据
    let data=[]
    let cols=3
    let defaultValue=selectedValues[openType]
    switch(openType){
      case 'area':
        data=[area,subway]
        cols=3
        break;
      case 'mode':
        data=rentType
        cols=1
        break;
      case 'price':
        data=price;
        cols=1
        break;
      default:
        break;
    }
    return  <FilterPicker key={openType} onCancle={this.onCancle} onSave={this.onSave} data={data} cols={cols} type={openType} defaultValue={defaultValue}/>
  }
  renderFilterMore(){
    const { openType,selectedValues,filtersData:{roomType, oriented, floor, characteristic} } = this.state
    if(openType!=='more'){
      return null
    }
    const data={roomType, oriented, floor, characteristic}
    const defaultValue=selectedValues.more
    return <FilterMore data={data} type={openType} onSave={this.onSave} defaultValue={defaultValue} onCancle={this.onCancle}/>
  }
  //渲染遮罩层div
  renderMask(){
    const {openType}=this.state
    const isHide = ['more',''].includes(openType)
    return (
      <Spring
        from={{opacity: 0}}
        to={{opacity: isHide ? 0 : 1}} 
      >
        {
          props=>{
            //说明遮罩层已经完成了动画效果隐藏了
            if(!props.opacity){
              return null 
            }
            return (
              <div 
              style={props}
              className={styles.mask} 
              onClick={()=>this.onCancle(openType)}/>
            )
          }
        }
      </Spring>
    )  
    // if(!['area','mode','price'].includes(openType)){
    //   return null
    // }
    // return (
    //   <Spring
    //     from={{opacity: 0}}
    //     to={{opacity: 1}}
    //   >
    //     {
    //       props=>{
    //         // console.log(props);
    //         return (
    //           <div 
    //           style={props}
    //           className={styles.mask} 
    //           onClick={()=>this.onCancle(openType)}/>
    //         )
    //       }
    //     }
    //   </Spring>
    // )            
  }
  render(){
    const {titleSelectedStatus}=this.state
    return (
      <div className={styles.root}>
        {/* 前三个菜单的遮罩层 */}
        {this.renderMask()}

        <div className={styles.content}>
          {/* 标题栏 */}
          <FilterTitle titleSelectedStatus={titleSelectedStatus} onClick={this.onTitleClick}/>

          {/* 前三个菜单对应的内容： */}
          {this.renderFilterPicker()}

          {/* 最后一个菜单对应的内容： */}
          {this.renderFilterMore()}
        </div>
      </div>
    )
  }
}
